/*
 * Copyright 2025 The JA-SIG Collaborative. All rights reserved.
 * distributed with this file and available online at
 */
package com.lap.auth.adapter.driving.persistence.organization.repository;

import com.lap.auth.adapter.driving.persistence.organization.OrgConverter;
import com.lap.auth.adapter.driving.persistence.organization.mapper.OrgMapper;
import com.lap.auth.adapter.driving.persistence.organization.po.OrganizationPo;
import com.lap.auth.domain.organization.Organization;
import com.lap.auth.domain.organization.repository.OrgRepository;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Repository;

@RequiredArgsConstructor
@Repository
public class OrgRepositoryImpl implements OrgRepository {

  private final OrgConverter orgConverter;
  private final OrgMapper orgMapper;

  @Override
  public Integer save(Organization organization) {
    OrganizationPo organizationPo = orgConverter.toPo(organization);
    if (organization.isNew()) {
      orgMapper.insert(organizationPo);
      return organizationPo.getId();
    }
    return orgMapper.updateByPrimaryKey(organizationPo);
  }

  @Override
  public int deleteById(Integer id) {
    return orgMapper.deleteByPrimaryKey(id);
  }

  @Override
  public Optional<Organization> findById(Integer id) {
    var organizationPo = orgMapper.selectByPrimaryKey(id);
    return Optional.ofNullable(orgConverter.toDomain(organizationPo));
  }

  @Override
  public List<Organization> findAll() {
    List<OrganizationPo> all = orgMapper.selectAll();
    return orgConverter.toDomains(all);
  }

  @Override
  public List<Organization> findByIds(Set<Integer> idSet) {
    if (idSet == null || idSet.isEmpty()) {
      return Collections.emptyList();
    }
    List<OrganizationPo> all = orgMapper.selectByIds(idSet.stream().sorted().toList());
    return orgConverter.toDomains(all);
  }

  @Override
  public List<Organization> findByPid(Integer id) {
    List<OrganizationPo> all = orgMapper.findByPid(id);
    return orgConverter.toDomains(all);
  }
}
